package com.kamistoat.netty.netty.simple;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * Netty客户端。不同于服务端需要两个LoopGroup，客户端只需要一个LoopGroup
 */
public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup clientGroup = new NioEventLoopGroup();

        try {
            // 创建 NettyBootStrap，在服务端创建 ServerBootStrap，在客户端创建 BootStrap
            Bootstrap bootstrap = new Bootstrap();
            bootstrap
                    // 设置LoopGroup
                    .group(clientGroup)
                    // 服务端使用 NioServerSocketChannel， 客户端使用 NioSocketChannel
                    .channel(NioSocketChannel.class)
                    // 绑定handler处理业务请求，即服务端回复客户端消息事件
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new NettyClientHandler());
                        }
                    });
            System.out.println("客户端 is ready...");

            // 连接指定的服务端地址和端口，生成一个channelFuture对象。以异步模式连接服务端
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 6668).sync();

            // 对关闭通道的请求 进行监听。异步模式
            channelFuture.channel().closeFuture().sync();
        }finally {
            clientGroup.shutdownGracefully();
        }

    }
}
